/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.controller.travel.pc;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.finalist.Setting;
import com.finalist.controller.admin.BaseController;
import com.finalist.entity.Admin;
import com.finalist.entity.BaseEntity.Save;
import com.finalist.plugin.StoragePlugin;
import com.finalist.service.AdminService;
import com.finalist.service.DepartureService;
import com.finalist.service.DestinationService;
import com.finalist.service.ProductCategoryService;
import com.finalist.service.ProductService;
import com.finalist.util.DateUtil;
import com.finalist.util.FreemarkerUtils;
import com.finalist.util.SettingUtils;

import freemarker.template.TemplateException;

/**
 * Controller - 关于风客
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Controller("joinController")
@RequestMapping("/travel/pc/join")
public class JoinController extends BaseController
{
	@Resource(name = "adminServiceImpl")
	private AdminService adminService;
	
	@Resource
	private List<StoragePlugin> storagePlugins;
	
	/**
	 * 加入
	 */
	@RequestMapping(value = "/join", method = RequestMethod.GET)
	public String join(ModelMap model) {
		model.addAttribute("activePage", "join");
		
		return "/travel/pc/join";
	}
	
	/**
	 * 加入风客--保存提交
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Admin admin, ModelMap model, RedirectAttributes redirectAttributes) {
		/*if (!isValid(admin, Save.class)) {
			return ERROR_VIEW;
		}*/
		
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
		admin.setUsername("newUser_"+df.format(new Date()));
		
		if (adminService.usernameExists(admin.getUsername())) {
			return ERROR_VIEW;
		}
		
		admin.setPassword(DigestUtils.md5Hex("000000"));
		admin.setEmail("000000@qq.com");
		admin.setIsEnabled(false);
		admin.setIsLocked(false);
		admin.setLoginFailureCount(0);
		admin.setLockedDate(null);
		admin.setLoginDate(null);
		admin.setLoginIp(null);
		admin.setOrders(null);
		
		try {
			String idHandsImg = admin.getIdHandsImg();
			String idFrontImg = admin.getIdFrontImg();
			String idBackImg = admin.getIdBackImg();
			
			Setting setting = SettingUtils.get();
			String uploadPath = FreemarkerUtils.process(setting.getImageUploadPath(), model);
			
			String uuid1 = UUID.randomUUID().toString();
			String uuid2 = UUID.randomUUID().toString();
			String uuid3 = UUID.randomUUID().toString();
			
			String idHandsImgPath = uploadPath + uuid1 + "-idcard." + getExtensionName(idHandsImg);
			String idFrontImgPath = uploadPath + uuid2 + "-idcard." + getExtensionName(idFrontImg);
			String idBackImgPath = uploadPath + uuid3 + "-idcard." + getExtensionName(idBackImg);
			
			Collections.sort(storagePlugins);
			for (StoragePlugin storagePlugin : storagePlugins) {
				if (storagePlugin.getIsEnabled()) {
					File idHandsImgFile = new File(storagePlugin.getUrl(idHandsImgPath));
					File idFrontImgFile = new File(storagePlugin.getUrl(idFrontImgPath));
					File idBackImgFile = new File(storagePlugin.getUrl(idBackImgPath));
					if (!idHandsImgFile.getParentFile().exists()) {
						idHandsImgFile.getParentFile().mkdirs();
					}
					if (!idFrontImgFile.getParentFile().exists()) {
						idFrontImgFile.getParentFile().mkdirs();
					}
					if (!idBackImgFile.getParentFile().exists()) {
						idBackImgFile.getParentFile().mkdirs();
					}
					
					admin.setIdHandsImg(storagePlugin.getUrl(idHandsImgPath));
					admin.setIdFrontImg(storagePlugin.getUrl(idFrontImgPath));
					admin.setIdBackImg(storagePlugin.getUrl(idBackImgPath));
				}
			}
			
			System.out.println("IdHandsImg: "+admin.getIdHandsImg());
			System.out.println("IdFrontImg: "+admin.getIdFrontImg());
			System.out.println("IdBackImg: "+admin.getIdBackImg());
			
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (TemplateException e1) {
			e1.printStackTrace();
		}
		
		try {
			adminService.save(admin);
			
			model.addAttribute("company", admin.getCompany());
			model.addAttribute("name", admin.getName());
			model.addAttribute("idNum", admin.getIdNum());
			model.addAttribute("paperNum", admin.getPaperNum());
			model.addAttribute("idHandsImg", admin.getIdHandsImg());
			model.addAttribute("idFrontImg", admin.getIdFrontImg());
			model.addAttribute("idBackImg", admin.getIdBackImg());
			model.addAttribute("address", admin.getAddress());
			model.addAttribute("phoneNum", admin.getPhoneNum());
			
			model.addAttribute("joinINSuccess", true);
			
			model.addAttribute("activePage", "join");
		} catch (Exception e) {
			e.printStackTrace();
			
			model.addAttribute("joinINFail", true);
		}
		
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		
		/*return "redirect:join.jhtml";*/
		return "/travel/pc/join";
	}
	
	/**
	 * 取得上传文件的后缀名
	 */
	public static String getExtensionName(String filename) {   
        if ((filename != null) && (filename.length() > 0)) {   
            int dot = filename.lastIndexOf('.');   
            if ((dot >-1) && (dot < (filename.length() - 1))) {   
                return filename.substring(dot + 1);   
            }   
        }   
        return filename;   
    }
}